﻿using System;
using System.Linq;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using System.Text;

namespace HeatMapPrototype
{
    public partial class Plot : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();

            SqlConnection connection = new SqlConnection(GetConnectionString());
            connection.Open();
            SqlCommand cmd = new SqlCommand();
            cmd = new SqlCommand("RetrieveHeatMapCoordinates", connection);
            cmd.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            
            da.Fill(dt);

            ltrPoints.Text = GetJsonString(dt);

            connection.Close();
            connection.Dispose();            
        }

        private string GetConnectionString()
        {
            return ConfigurationManager.AppSettings["SQLConn"];
        }

        public static string GetJsonString(DataTable dt)
        {
            string[] strDc = new string[dt.Columns.Count];

            string headStr = string.Empty;

            for (int i = 0; i < dt.Columns.Count; i++)
            {
                strDc[i] = dt.Columns[i].Caption;
                headStr += strDc[i] + ": " + strDc[i] + i.ToString() + "¾" + ",";
            }

            headStr = headStr.Substring(0, headStr.Length - 1);

            StringBuilder sb = new StringBuilder();            

            //The following line has a MAX value. This value should be set based on 
            //the max count of clicks relating to the frequency. The higher the max
            //is set, the more point counts it will take to show blue, yellow, red, etc...
            sb.Append("{max: 10, data: [");

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string tempStr = headStr;
                sb.Append("{");

                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    tempStr = tempStr.Replace(dt.Columns[j] + j.ToString() +
                    "¾", dt.Rows[i][j].ToString());
                }
                sb.Append(tempStr + "},");
            }

            sb = new StringBuilder(sb.ToString().Substring(0, sb.ToString().Length - 1));

            sb.Append("]}");
            return sb.ToString();
        }
    }
}